/*
 * @Author: venom
 * @Date: 2021-03-03 16:55:39
 * @LastEditors: venom
 * @LastEditTime: 2021-03-03 16:56:42
 * @Description: 
 * @FilePath: \venom-nacos-sdk\src\asyn.rs
 * MIT
 */


use common_uu::IResult;
use reqwest::{Method, Response, StatusCode};
use crate::params::Params;

pub struct NacosClient {
    host: String,
}


impl NacosClient {
    pub fn new(host: String) -> NacosClient {
        NacosClient {
            host
        }
    }

    pub async fn action(&self, method: impl Into<Method>, url: &str, params: Params) -> IResult<String> {
        let host = &self.host;
        let query = &params.query;
        let url = if !params.query.is_empty() { format!("{host}/{url}?{query}") } else { format!("{host}/{url}") };
        let r = reqwest::Client::new().request(method.into(), url).multipart(params.forms).send().await?;
        check_response_status_code(r).await
    }


    // pub  fn get_config(&self,dataId:String,  group:String, tenant:String)->String{
    //    let  uri = format!("http:://{}/nacos/v1/cs/configs?dataId={}&group={}&tenant={}",&self.host,dataId,group,tenant);
    //    let text = match reqwest::blocking::get(uri.as_str()) {
    //        Ok(t) =>t,
    //        Err(e) =>{
    //                 println!("error");
    //                 return String::from("helloword")
    //        }
    //    };

    //    return String::from("helloword")
    // }
    #[allow(non_snake_case)]
    pub async fn getConfig(&self, data_id: String, group: String, tenant: String) -> Result<String, String> {
        let uri = format!("{}/nacos/v1/cs/configs?dataId={}&group={}&tenant={}", &self.host, data_id, group, tenant);
        println!("{}", uri);
        let res = match reqwest::get(uri.as_str()).await {
            Ok(t) => t.text().await.unwrap(),
            Err(_e) => {
                println!("error");
                return Err(String::from("NoGo"));
            }
        };
        println!("{}", res);
        return Ok(res);
    }
}

async fn check_response_status_code(resp: Response) -> IResult<String> {
    match resp.status() {
        StatusCode::OK => return Ok(resp.text().await?),
        s => Err("response status: ".to_string() + &s.to_string())?,
    }
}


#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        let data_id = "node_gateway".to_string();
        let group = "dev".to_string();
        let tenant = "venom_server".to_string();
        assert_eq!(tokio_test::block_on(NacosClient::new("http://47.106.81.32:8848".to_string()).getConfig(data_id, group, tenant)), Ok("1000".to_string()));
    }
}